﻿//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using Localization.Repository.Repositories;
//using Localization.Repository.Repositories.FileBase;
//using System.Globalization;
//using System.IO;

//namespace Localization.Repository
//{
//    public class ResourceService
//    {
//        private IResourceRepository _resourceRepository;
//        public IResourceRepository ResourceRepository
//        {
//            get { return _resourceRepository = _resourceRepository ?? new FileResourceRepository(); }
//            set { _resourceRepository = value; }
//        }

//        public void AddClassKey(ResourceClassKey classKey)
//        {
//            if (GetClassKeys().FirstOrDefault(f => 0 == string.Compare(f.ClassKeyName, classKey.ClassKeyName, true)) != null)
//                return;

//            ResourceRepository.PersistClassKey(classKey);
//        }

//        public IEnumerable<ResourceClassKey> GetClassKeys()
//        {
//            var query = from r in ResourceRepository.FindClassKeys().AsEnumerable()
//                        select new ResourceClassKey { ID = r.ClassKeyID, ClassKeyName = r.ClassKeyName };
//            return query.ToList();
//        }

//        public ResourceClassKey GetClassKeyByName(string classKeyName)
//        {
//            return GetClassKeys().FirstOrDefault(f => 0 == string.Compare(f.ClassKeyName, classKeyName, true));
//        }

//        public ResourceClassKey ModifyClassKey(ResourceClassKey classKey)
//        {
//            if (string.IsNullOrEmpty(classKey.ClassKeyName))
//                throw new ArgumentException("Class key name cannot be null");
//            ResourceRepository.PersistClassKey(classKey);
//            return classKey;
//        }

//        public IEnumerable<ResourceCulture> GetCultures()
//        {
//            var query = from r in ResourceRepository.FindCultures().AsEnumerable()
//                        select new ResourceCulture(r.CultureID, r.CultureCode, r.IsDefault);
//            return query.ToList();
//        }

//        public bool ValidateCulture(string cultureName)
//        {
//            try
//            {
//                CultureInfo ci = new CultureInfo(cultureName);
//                return true;
//            }
//            catch { }
//            return false;
//        }

//        public IEnumerable<ResourceValue> SearchResourceText(string searchText, bool searchBeginsWith, string classKeyName, CultureInfo culture)
//        {
//            ResourcesDataSet dataSet = ResourceRepository.LoadRepository();

//            var query = from r in dataSet.ResourceValues
//                        join c in dataSet.ResourceCultures
//                        on r.CultureID equals c.CultureID
//                        where c.CultureCode == culture.Name
//                        select r;

//            if (!string.IsNullOrEmpty(classKeyName))
//            {
//                query = from r in query
//                        join ck in dataSet.ResourceClassKeys
//                        on r.ResourceKeysRow.ClassKeyID equals ck.ClassKeyID
//                        where 0 == string.Compare(ck.ClassKeyName, classKeyName, true)
//                        select r;
//            }

//            //if (translated.HasValue)
//            //    criteria.Add(Expression.Eq("IsTranslated", translated));

//            if (!string.IsNullOrEmpty(searchText))
//            {
//                if (searchBeginsWith)
//                    query = query.Where(r => r.ResourceValue.StartsWith(searchText, true, CultureInfo.InvariantCulture));
//                else
//                    query = query.Where(r => r.ResourceValue.Contains(searchText));
//            }

//            var results = from r in query
//                          select new ResourceValue(
//                              r.ResourceValueID,
//                              new ResourceKey(
//                                  r.ResourceKeysRow.ResourceKeyName,
//                                  new ResourceClassKey
//                                  {
//                                      ID = r.ResourceKeysRow.ResourceClassKeysRow.ClassKeyID,
//                                      ClassKeyName = r.ResourceKeysRow.ResourceClassKeysRow.ClassKeyName
//                                  },
//                                  r.ResourceKeysRow.Comment),
//                              new ResourceCulture(
//                                  r.ResourceCulturesRow.CultureID,
//                                  r.ResourceCulturesRow.CultureCode,
//                                  r.ResourceCulturesRow.IsDefault),
//                              r.ResourceValue,
//                              r.ResourceKeysRow.Comment);

//            return results.ToArray();
//        }

//        public ResourceCulture GetDefaultCulture()
//        {
//            return (from r in GetCultures()
//                    where r.IsDefault
//                    select r).FirstOrDefault();
//        }

//        public void AddNewCulture(ResourceCulture resourceCulture)
//        {
//            if (GetCultures().FirstOrDefault(f => f.Name == resourceCulture.Name) != null)
//                return;

//            ResourceRepository.AddCulture(resourceCulture);

//            ResourcesDataSet dataSet = ResourceRepository.LoadRepository();

//            // create a list of resources to add for new culture value
//            var query = from r in dataSet.ResourceValues
//                        join c in dataSet.ResourceCultures
//                        on r.CultureID equals c.CultureID
//                        where c.IsDefault
//                        select new ResourceValue(
//                            0,
//                            new ResourceKey { Name = r.ResourceKeysRow.ResourceKeyName },
//                            resourceCulture,
//                            r.ResourceValue,
//                            null);

//            // insert new recourds
//            ResourceRepository.PersistResource(query.ToList());

//            if (resourceCulture.IsDefault)
//                ResourceRepository.SetDefaultCulture(resourceCulture.Name);
//        }

//        public void AddResource(string name, string value, string classKeyName, string comment)
//        {
//            ResourceClassKey ck = GetClassKeys().FirstOrDefault(f => 0 == string.Compare(f.ClassKeyName, classKeyName, true));
//            if (ck == null)
//                throw new InvalidOperationException("Class key was not found.");

//            // check that resource doesn't already exist
//            ResourceValue existing = GetResource(name, classKeyName, GetDefaultCulture().GetCultureFromName());
//            if (existing != null)
//                return;

//            ResourceKey rk = new ResourceKey(name, ck, comment);

//            // save resource key
//            ResourceRepository.PersistResourceKey(rk);

//            List<ResourceValue> resourcesToAdd = new List<ResourceValue>();

//            foreach (ResourceCulture rc in GetCultures())
//                resourcesToAdd.Add(new ResourceValue(rk, rc, value));

//            ResourceRepository.PersistResource(resourcesToAdd);
//        }

//        public void RemoveResourceKey(string name, string classKeyName)
//        {
//            throw new NotImplementedException();
//        }

//        public ResourceValue GetDefaultResource(string name, string classKeyName)
//        {
//            throw new NotImplementedException();

//            //return GetResources(name, classKeyName).FirstOrDefault(r => r.Culture.IsDefault);
//        }

//        public IEnumerable<ResourceValue> GetResources(string name, string classKeyName)
//        {
//            var result = from v in ResourceRepository.FindResourceValues()
//                         join k in ResourceRepository.FindResourceKeys()
//                         on v.ResourceKey.ID equals k.ID
//                         join ck in ResourceRepository.FindClassKeys()
//                         on k.ClassKey.ID equals ck.ID
//                         join c in ResourceRepository.FindCultures()
//                         on v.Culture.ID equals c.ID
//                         where 0 == string.Compare(k.Name, name, true)
//                         && 0 == string.Compare(ck.ClassKeyName, classKeyName, true)
//                         select new ResourceValue(
//                             v.ResourceKey.ID,
//                             new ResourceKey(
//                                 k.Name,
//                                 new ResourceClassKey { ID = ck.ID, ClassKeyName = ck.ClassKeyName },
//                                 k.Comment),
//                                 new ResourceCulture(c.ID, c.Name, c.IsDefault),
//                                 v.Value
//                             );

//            return result.ToArray();
//        }

//        public ResourceValue GetResource(string name, string classKeyName, CultureInfo culture)
//        {
//            return GetResources(name, classKeyName).FirstOrDefault(r => r.Culture.Name == culture.Name);
//        }

//        public void ModifyDefaultCulture(string name, string value, string comment, string classKeyName)
//        {
//            // need to set all exiting resources to not translated.
//            ResourceValue resource = GetResource(name, classKeyName, GetDefaultCulture().GetCultureFromName());
//            if (resource == null)
//                throw new InvalidOperationException(string.Format("Unable to find resource [{0}] with class key [{1}]", name, classKeyName));

//            foreach (var c in GetCultures())
//                Translate(name, value, classKeyName, c.GetCultureFromName());
//        }

//        public void Translate(string name, string value, string classKeyName, CultureInfo culture)
//        {
//            if (culture == null)
//                throw new ArgumentNullException("culture");
//            if (string.IsNullOrEmpty(value))
//                throw new ArgumentNullException("value");
//            if (string.IsNullOrEmpty(classKeyName))
//                throw new ArgumentNullException("classKeyName");

//            // get resouce to edit
//            ResourceValue resource = GetResource(name, classKeyName, culture);
//            if (resource == null)
//                throw new ArgumentNullException(string.Format(
//                    "Cannot find resource value for culture [{0}] and resource name [{1}].",
//                    culture.Name,
//                    name));

//            // check that this is not the default culutre
//            //ResourceCulture defaultCulture = GetDefaultCulture();
//            //if (resource.Culture.Name == defaultCulture.Name)
//            //    throw new ArgumentException(string.Format("Cannot translate default culutre.  Culture: [{0}]." + culture.Name));

//            resource.IsTranslated = false;
//            resource.Value = value;

//            ResourceRepository.PersistResource(resource);
//        }

//        public IEnumerable<ResourceValue> UnTranslatedValues(string classKeyName, CultureInfo culture)
//        {
//            ResourcesDataSet dataSet = ResourceRepository.LoadRepository();

//            var query = from r in dataSet.ResourceValues
//                        join c in dataSet.ResourceCultures
//                        on r.CultureID equals c.CultureID
//                        where c.CultureCode == culture.Name
//                            && !r.IsTranslated
//                            && r.ResourceKeysRow.ResourceClassKeysRow.ClassKeyName == classKeyName
//                        select new ResourceValue(
//                            r.ResourceValueID,
//                            new ResourceKey { Name = r.ResourceKeysRow.ResourceKeyName },
//                            new ResourceCulture(culture),
//                            r.ResourceValue,
//                            null);
//            return query;
//        }

//        public void GenereateResourceFiles(string classKey, string outputFolder, ResourceFileType fileType)
//        {
//            if (!outputFolder.EndsWith(@"\"))
//                outputFolder += @"\";

//            // see if dir exists
//            if (!Directory.Exists(outputFolder))
//                Directory.CreateDirectory(outputFolder);

//            //StringBuilder batchFileText = new StringBuilder();
//            //batchFileText.AppendLine("@echo off");
//            //string runtimeDir = System.Runtime.InteropServices.RuntimeEnvironment.GetRuntimeDirectory();
//            //batchFileText.AppendLine(
//            //    "set al_exe=\""
//            //    + runtimeDir.Substring(0, runtimeDir.LastIndexOf("v")) + "v2.0.50727"
//            //    + "\\al.exe\"");

//            // cycle each class key
//            ResourceClassKey ck = GetClassKeyByName(classKey);
//            if (ck == null)
//                throw new ArgumentNullException("Class key could not be resolved.");

//            // look through each culture and create assembly
//            foreach (ResourceCulture culture in GetCultures())
//            {
//                string fileName = null;
//                string currentFolder = null;

//                switch (fileType)
//                {
//                    case ResourceFileType.DotNet_Resource:
//                        if (culture.IsDefault)
//                        {
//                            fileName = string.Format("{0}.resources", ck.ClassKeyName);
//                            currentFolder = outputFolder;
//                        }
//                        else
//                        {
//                            fileName = string.Format("{0}.{1}.resources", ck.ClassKeyName, culture.Name);
//                            currentFolder = string.Format("{0}\\{1}", outputFolder, culture.Name);
//                            if (!Directory.Exists(currentFolder))
//                                Directory.CreateDirectory(currentFolder);
//                        }
//                        break;
//                    case ResourceFileType.DotNet_ResX:
//                        if (culture.IsDefault)
//                        {
//                            fileName = string.Format("{0}.resx", ck.ClassKeyName);
//                            currentFolder = outputFolder;
//                        }
//                        else
//                        {
//                            fileName = string.Format("{0}.{1}.resx", ck.ClassKeyName, culture.Name);
//                            currentFolder = outputFolder;
//                            if (!Directory.Exists(currentFolder))
//                                Directory.CreateDirectory(currentFolder);
//                        }
//                        break;
//                    case ResourceFileType.Android_ResourceFiles:
//                        fileName = ck.ClassKeyName;
//                        if (culture.IsDefault)
//                            currentFolder = outputFolder + @"\values";
//                        else
//                            currentFolder = outputFolder + @"\values-" + culture.Name;
//                        if (!Directory.Exists(currentFolder))
//                            Directory.CreateDirectory(currentFolder);
//                        break;

//                }

//                IEnumerable<ResourceValue> resources =
//                    SearchResourceText(null, true, ck.ClassKeyName, culture.GetCultureFromName());

//                // generate files
//                ResourceFileHelper.GenerateResourceFile(fileType, currentFolder, fileName, resources);

//                //// create assembly linker batch file of .net res files
//                //if (fileType == ResourceFileType.DotNet_ResX || fileType == ResourceFileType.DotNet_Resource)
//                //{
//                //    // create batch to run al.exe
//                //    if (culture.IsDefault)
//                //        batchFileText.AppendLine(
//                //            string.Format("%al_exe% /t:lib /embed:{0} /culture:{1} /out:{2}.resources.dll",
//                //            fileName,
//                //            culture.Name,
//                //            ck.ClassKeyName));
//                //    else
//                //        batchFileText.AppendLine(
//                //            string.Format("%al_exe% /t:lib /embed:{1}\\{0} /culture:{1} /out:{1}\\{2}.resources.dll",
//                //            fileName,
//                //            culture.Name,
//                //            ck.ClassKeyName));
//                //}
//            }

//            // write batch file
//            //System.IO.File.WriteAllText(outputFolder + "\\generate_satellites.bat", batchFileText.ToString());
//        }
//    }
//}
